package org.sam.beatles.widget;

import java.util.Collection;

import javax.swing.JComponent;

import org.sam.beatles.MainFrameContainer;
import org.sam.beatles.event.LogEvent;
import org.sam.swing.ComponentSearch;
import org.sam.swing.table.JSTable;
import org.sam.swing.table.JSTableModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;

import com.metsci.glimpse.docking.Tile;
import com.metsci.glimpse.docking.View;

/**
 * 接收系统日志操作
 * 
 * @author li
 *
 */
@Controller
public class LogEventWidget {

	/**
	 * 主窗口
	 */
	@Autowired
	private MainFrameContainer view;

	/**
	 * 接收
	 * 
	 * @param event
	 */
	@SuppressWarnings("unchecked")
	@EventListener(LogEvent.class)
	@Async
	public void logEventHandler(LogEvent event) {
		if (event == null)
			return;

		if (this.view == null)
			return;

		if (!this.view.getViewParts().containsKey(MainFrameContainer.TILE_LOG))
			return;

		JComponent jComponent = this.view.getViewParts().get(MainFrameContainer.TILE_LOG);
		if (jComponent == null || !(jComponent instanceof Tile))
			return;

		Tile tile = (Tile) jComponent;

		try {
			View v = tile.view(0);
			ComponentSearch c = (ComponentSearch) v.component.v();
			JSTable table = (JSTable) c.findViewById("table");
			JSTableModel<Collection<Object[]>> model = (JSTableModel<Collection<Object[]>>) table.getModel();
			model.addRow(new Object[] { 0, event.getGroup() , event.getLevel(), event.getMsg()});
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
